/**
 * Created by Administrator on 15-6-19.
 */
var Calendar = RichBase.extend({
	statics : {},
	EVENTS : {
		"click" : {
			".close" : "onCloseClick",
			".title .lastmonth" : "onPrevmonthClick",
			".title .nextmonth" : "onNextmonthClick",
			".detail" : "onDateSelect"
		}
	},
	init : function(opt){
		this.container = opt.container;

	},
	onCloseClick : function(that,e){
		that.close(null);
	},
	onNextmonthClick : function(that,e){
		var nextmonth = CalendarCore.nextMonth(that.currentDate);
		that.show(nextmonth);
	},
	onDateSelect : function(that,e){
		var tarDateBox = $(e.currentTarget);
		var currentDate = that.currentDate;
		if(currentDate.length==10) currentDate = currentDate.substring(0,7);
		var tarDate = tarDateBox.find(".dateNum").text();
		tarDate = currentDate+"-"+tarDate;
		that.fire("onSelect",tarDate);
		if(tarDateBox.hasClass("valid")){
			that.fire("onValidSelect",tarDate);
			that.close(tarDate);
		}else{
			that.fire("onUnvalidSelect",tarDate);
		}
	},
	onPrevmonthClick : function(that,e){
		var prevmonth = CalendarCore.prevMonth(that.currentDate);
		that.show(prevmonth);
	},
	show : function(date){
		date = date || CalendarCore.gettoday();
		this.container.show().html(CalendarCore.outputHtml(date));
		this.currentDate = date;
	},
	close : function(date){
		this.container.hide();
		this.fire("onClose",date);
	}
});
//场次列表
var ChangciList = RichBase.extend({
	statics : {},
	EVENTS : {
		"click" : {
			"#changciUl .changciItem" : "onChangciClick"
		}
	},
	init : function(opt){
		var that = this;
		this.container = $("#changciListWrap");
		this.listUl = $("#changciUl");
		this.changciInp = $("#selectchangciInput");
		this.container.click(function(){ that.hide()});
	},
	abort : function(){ this.xhr && this.xhr.abort() },
	show : function(){
		var inp = this.changciInp;
		var offset = inp.offset();
		this.container.show().children().css({
			left : offset.left,
			top : offset.top + inp.innerHeight() + 2
		})
	},
	hide : function(){
		this.container.hide();
	},
	query : function(date){
		var that = this;
		var lid = $("#gLidHidInp").val();
		var venueId = $("#venueIdHidInp").val();
		if(!date) return false;
		this.abort();
		this.xhr = PFT.Ajax({
			url : "call/before_ph_data.php",
			type : "GET",
			dataType : "json",
			data : {
				m : "round",
				date : date,
				venus_id : venueId
			},
			loading : function(){
				that.listUl.html('<li class="loading" style="height:200px; width:383px; line-height:200px; text-align:center;">正在加载...</li>');
			},
			removeLoading : function(){ that.listUl.html()},
			timeout : function(){ alert("网络请求超时，请稍后重试")},
			serverError : function(){ alert("网络请求出错，请稍后重试")}
		},function(res){
			var list = [];
			if(res.status=="success"){
				for(var i in res.rounds){
					var d = {};
					var r = res.rounds[i];
					var area_storage = r["area_storage"];
					var storageArr = [];
					for(var i in area_storage){
						storageArr.push(i+","+area_storage[i]);
					}
					d["id"] = r["id"];
					d["title"] = r["round_name"];
					d["begintime"] = r["bt"];
					d["endtime"] = r["et"];
					d["storage"] = r["storage"];
					d["area_storage"] = storageArr.join("|");
					list.push(d);
				}
			}else{
				alert(res.msg || "查询场次信息出错，请稍后重试");
			}
			var html = that.buildHtml(list);
			that.listUl.html(html);
			setTimeout(function(){
				if(res.rounds.length){
					that.listUl.children().first().trigger("click");
				}else{
					that.changciInp.val("该日期没有场次安排");
				}
			},10)
		})
	},
	buildHtml : function(data){
		var that = this;
		var tpl = $("#changciListTpl").html();
		var html = "";
		for(var i in data){
			var changci = data[i];
			html += that.parseTemplate(tpl,changci);
		}
		return html
	},
	onChangciClick : function(that,e){
		var tarLi = $(e.currentTarget);
		var time = tarLi.attr("data-time");
		var area_storage = tarLi.attr("data-areastorage");
		var roundId = tarLi.attr("data-id");
		if(tarLi.hasClass("active")) return false;
		that.hide();
		tarLi.addClass("active").siblings().removeClass("active");
		$("#roundIdHidInp").val(roundId)
		that.fire("changciChange",time,area_storage);
	}
});
//产品列表

//main
var Order = RichBase.extend({
	statics : {},
	EVENTS : {
		"click" : {
			"#selectDateTrigger" : "onSelectDateInputClick",
			"#selectDateInput" : "onSelectDateInputClick",
			//"#show_all" : "data_open"
		}
	},
	statics : {
		currentPage : 0,
		last : "",
		oData : {},
		queryState : {
			loading : '<li class="loading" style="text-align:center; line-height:1; height:400px;"><p style="color:#aeaeae; font-size:12px; padding-top:300px;">加载数据...</p><img src="images/other/loading_1.gif" alt="" /></li>',
			empty : '<li class="loading" style="text-align:center; line-height:1; height:400px;"><p style="color:#aeaeae; font-size:12px; padding-top:300px;">没有产品...</p></li>',
			fail : '<li class="loading" style="text-align:center; line-height:1; height:400px;"><p style="color:#aeaeae; font-size:12px; padding-top:300px;">请求失败...</p></li>',
			unlogin : '<li class="loading" style="text-align:center; line-height:1; height:400px;"><p style="color:#aeaeae; font-size:12px; padding-top:300px;">登录过期，请重新登录...</p></li>',
			timeout : '<li class="loading" style="text-align:center; line-height:1; height:400px;"><p style="color:#aeaeae; font-size:12px; padding-top:300px;">网络请求超时...</p></li>',
			serverError : '<li class="loading" style="text-align:center; line-height:1; height:400px;"><p style="color:#aeaeae; font-size:12px; padding-top:300px;">请求出错...</p></li>'
		},
		getProv : function(id){
			var prov = "";
			var p = PROVINCES;
			if(!id) return prov;
			for(var i in p){
				var areaid = p[i]["area_id"];
				if(areaid==id){
					prov = p[i]["area_name"];
					break;
				}
			}
			return prov;
		},
		isObjEmpty : function(obj){
			for(var i in obj){
				return false;
			}
			return true;
		}
	},
	init : function(opt){
		//alert("ddd")
		this.data_limit();
		this.data_list();
		this.container = opt.container;
		this.dateInp = $("#selectDateInput");
		this.changciInp = $("#selectchangciInput");
		this.calendar = this.importCalendar();
		this.product = this.importProduct();
		var defaulttime = this.dateInp.val();
	},
	data_list : function(opt){
		var that = this;
		var opt = opt || {};
		var pageSize = opt.pageSize || 15;
		var last = opt.last || "";
		var provice = opt.provice || "";
		var city = opt.city || "";
		var title = opt.title || "";
		var ttimeout = opt.ttimeout || 20 * 60 * 1000;
		
		var data = {
			lid:7036
		};
		var url = "http://www.12301.cc/a/salePros.php?act=prods&";
		var url_id ="1";
		var listUl = $("#mlistUl");
		var pagenavW = $("#pagenavW");
		var status = this.statics.queryState;
		PFT.Ajax({
			//url : "product_package.html",
			url : url,
			type : "GET",
			dataType : "json",
			ttimeout : ttimeout,
			data : data,
			loading : function(){
				listUl.html(status["loading"]); 
				pagenavW.hide();
			},
			removeLoading : function(res){
				that.statics.last = "";
				that.statics.currentPage += 1;
				listUl.html("");
				pagenavW.show();
			},
			timeout : function(){ listUl.html(status["timeout"]);},
			serverError : function(){ listUl.html(status["serverError"]);}
		},function(res){
			var code = res.code;
			var lists = res.lists;
			var last = res.last;
			var total = res.total;
			if(total>5){
				$(".show_class").css("display","block")
			}
			if(code==200){
				if(!that.statics.isObjEmpty(lists)){
					that.statics.oData[that.statics.currentPage] = res;
					//console.log(that.statics.oData[that.statics.currentPage])
					that.buildHtml(res);
				}else{
					listUl.html(status["empty"]);
					if(provice) that.fire("search_empty",res);
				}
				that.statics.last = last;
				if(!last){
					that.fire("no_next",res);
				}else{
					that.fire("has_next",res);
				}
			}else if(code==0){
				listUl.html(status["unlogin"]);
			}else{
				listUl.html(status["fail"]);
			}
		})
	},
	data_limit : function(){
		$(".ticket_con").animate({height:"285px"});
		$(".ticket_con").addClass("overflow_h");
		$(".show_class").text("显示全部");
	},
	// data_open : function(){
		// $(".ticket_con").css({height:"auto"});
		// $(".ticket_con").removeClass("overflow");
		// $(".show_class").text("隐藏部分");
	// },
	 data_open : function(){
	 
	},
	buildHtml : function(res){
		var that = this;
		var code = res.code;
		var lists = res.lists;
		var str = "";
		var last = res.last;
		// $(this).one("click", function(){
			// $(".prevBtn").attr("data-mid",last);
		// });
		var item_a = $("#itemTpl").html();
		var item_div = $("#itemTpl_tr").html();
		var item_con = $("#itemTpl_con").html();
		var result = "";
		var listUl = $("#mlistUl");
		var pagenavW = $("#pagenavW");
		var data = lists;
			str += '<table class="ticket_table" >';
			str += '<thead>';
			str += '<tr>';
			str += '<th class="th1">门票类型</th>';
			str += '<th class="th2">结算价格</th>';
			str += '<th class="th3">预订数量</th>';
			str += '<th class="th4">合计</th>';
			str += '<th class="th5">选择</th>';
			str += '</th>';
			str += '</thead>';
		for(var i in data){
			is_data_empty = false;
		
			str += '<tbody  class="ticket_c" data="1" data-i="" id="proTable">';
			str += '<tr>';
			str += '<td class="td1">'+data[i]["title"]+'</td>';
			str += '<td>&yen;'+i+'</td>';
			str += '<td class="coutTd">';
			str += '<a href="javascript:void(0)" class="iconfont add_icon sub subBtn countBtn">&#xe600;</a>';
			str += '<input class="ticket_num ui-form-txt-a formInp countInp" data-tprice="'+i+'" type="text" value="0">';
			str += '<a href="javascript:void(0)" data="1" data-i="" class="iconfont cut_icon plus countBtn plusBtn">&#xe601;</a>';
			str += '</td>';
			str += '<td class="smallTotalNum num">￥0</td>';
			str += '<td><a href="javaEnabled:void(0)" class="iconfont  selected">&#xe605;</a><a href="javaEnabled:void(0)" class="iconfont select">&#xe606;</a></td>';
			str += '</tr>';
			str += '</tbody>';
			 
		}str += '</table>';
		$(".ticket_con").html(str);
	},
	//载入日历模块
	importCalendar : function(){ 
		
		var that = this;
		var proTable = $("#ticket_presale");
		return new Calendar({container:$("#calendarWrap")}).on("onValidSelect",function(date){
			$("#sumtnum").text(0);
			$("#summoney").text(0);
			proTable.find(".countInp").val(0);
			//proTable.find(".plusBtn").addClass("disable");
			//proTable.find(".subBtn").addClass("disable");
			proTable.find(".storage_td").text("-");
			that.dateInp.val(date);
			//date && that.changeciList.query(date);
		});
	},
	//载入产品列表模块
	importProduct : function(){
		var that = this;
		return new Product({container:$("#proTable")});
	},
	//点击日历模块
	onSelectDateInputClick : function(that,e){
		var date = that.dateInp.val();
		that.calendar.show(date);
	}
});
var tarBtn = RichBase.extend({
	statics : {},
	EVENTS : {
		"focus" : {
			".formInp" : "onInputFocus"
		},
		"blur" : {
			".formInp" : "onInputBlur"
		},
		"click" : {
			".ticket_c" : "BtnClick"
		 }
	},
	init : function(opt){                                    },
	onInputFocus : function(that,e){
		var tarInp = $(e.currentTarget);
		tarInp.attr("data-orign",tarInp.val());
	},
	BtnClick : function(that,e){
		//alert("")
		var tarBtn = $(e.currentTarget);
		tarBtn.attr("data","0");
		var hi = tarBtn.attr("data-i")
		//var active_list_a = tarBtn.parents(".ticket_con").find('.ticket_table .plus');
		var active_list_a = tarBtn;
		$(".ticket_c").each(function(){
			var active = $(this).attr("data");
			//alert(active)
			if(active=="0"){ 
				//alert("0")
				$(this).css('color','');
				$(this).addClass("blue");
				//$(this).find('.select').text("&#xe605;")
				$(this).find('.select').css("display","none");
				$(this).find('.selected').css({
					"display":"block",
					"text-decoration":"none",
					"font-size":"1.1em"
				});
				//alert("这个"+hi);
				tarBtn.attr("data","1");
				}
			else{
				//alert("1")
				$(this).css('color','#999');
				$(this).removeClass("blue");
				$(this).find('.select').css("display","block");
				$(this).find('.selected').css("display","none");
				//$(this).find('.select').text("&#xe606;")
				//$(this).css('color','#999');
			
				//$(this).css('color','');
				//$(".ticket_table").not($(this))css('color','#999');
			}
		});
		
		
		
	},
	
	
	
});
var search_all = RichBase.extend({
	
	statics : {},
	EVENTS : {
		"focus" : {
			".formInp" : "onInputFocus"
		},
		"blur" : {
			".formInp" : "onInputBlur"
		},
		"click" : {
			// ".ticket_c" : "BtnClick"
			".coutTd .countBtn" : "onCountBtnClick"
		 }
	},
	init : function(opt){
		this.onload();
	},
	
	onload : function(that,e){
		var that = this;
		$('#prodSearchInp').text('');
		$(".cleartxt").click(function(){
			$('#prodSearchInp').val('');
			$(this).css("display","none");
			$("#lid_id").val('');
		});
		$("#prodSearchInp").keyup(function(){
			var sth=$('#prodSearchInp').val();
			var i=0;
			$("#prodList li").each(function(){
				var n=$(this).text().indexOf(sth);
				if(n==-1){
					$(this).css("display","none");
				}else{
					i+=1
					$(this).css("display","block");
				}
			});
			if(i==0){
				$(".searchmsg").css("display","block");
				$("#prodList").css("display","none");
			}else{
				$(".searchmsg").css("display","none");
				$("#prodList").css("display","block");
			}
		});
		PFT.Ajax({
			url : "http://www.12301.cc/a/salePros.php?act=lands",
			type : "post",
			dataType : "json",
		},function(res){
			
			that.list_search(res); 
		})
	},
	
	list_search : function(data){
	
	var that = this;
	var list = data.lists;
	for(var i=0;i<list.length;i++){
	    $("#prodList").append("<li data="+list[i].id+">"+list[i].title+"</li>");
	}
	$("#prodList li").eq(0).addClass("setbg");
	$("#prodList li").click(function(){
		$(".must_sec").css("display","none");
		$("..content_pre .ticket_con").css("display","block");
		var i=$(this).index();
		$("#prodSearchInp").val(list[i].title);
		$("#prodList li").removeClass("setbg");
		$("#prodList li").eq(i).addClass("setbg");
		$("#prodList").css("display","none"); 
		$("#lid_id").val(list[i].id);
        $(".cleartxt").css("display","block");
	});
	$("#prodSearchInp").click(function(){
		
        if($("#prodList").css("display")=='block')
            $("#prodList").css("display","none");
        else
		    $("#prodList").css("display","block");
		});
	}
	});
var Product = RichBase.extend({
	statics : {},
	EVENTS : {
		"focus" : {
			".formInp" : "onInputFocus"
		},
		"blur" : {
			".formInp" : "onInputBlur"
		},
		"click" : {
			// ".ticket_c" : "BtnClick"
			".coutTd .countBtn" : "onCountBtnClick"
		 }
	},
	init : function(opt){                                    },
	onInputFocus : function(that,e){
		var tarInp = $(e.currentTarget);
		tarInp.attr("data-orign",tarInp.val());
	},
	onInputBlur : function(that,e){
		var tarInp = $(e.currentTarget);
		var areaid = tarInp.attr("data-areaid");
		var storage = tarInp.attr("data-storage");
		var orignVal = tarInp.attr("data-orign");
		var val = tarInp.val();
		if(!val || !PFT_GLOBAL.U.isPositiveNum(val)){
			tarInp.val(orignVal);
			return false;
		}
		that.changeCount(tarInp,areaid,storage,orignVal,val);
	},
	onCountBtnClick : function(that,e){
		var tarBtn = $(e.currentTarget);
		tarBtn.attr("data","0");
		var hi = tarBtn.attr("data-i")
		//var active_list_a = tarBtn.parents(".ticket_con").find('.ticket_table .plus');
		var active_list_a = tarBtn;
		// $(".plus").each(function(){
			// var active = $(this).attr("data");
			// //alert(active)
			// if(active=="0"){ 
				// //alert("0")
				// $(this).parents(".ticket_c").css('color','');
				// $(this).parents(".ticket_c").addClass("blue");
				// //tarBtn.parents(".ticket_con").find('.ticket_table .plus');
				// //alert("这个"+hi);
				// tarBtn.attr("data","1");
				// }
			// else{
				// //alert("1")
				// $(this).parents(".ticket_c").css('color','#999');
				// $(this).parents(".ticket_c").removeClass("blue");
				// //$(this).css('color','#999');
				// $(this).find()
				// //$(this).css('color','');
				// //$(".ticket_table").not($(this))css('color','#999');
			// }
		// });
	
		//var tarBtn = $(e.currentTarget);
		var tarInp = tarBtn.siblings(".formInp");
		var val = tarInp.val(), newVal=0;
		
		var storage = tarInp.attr("data-storage");
		var areaid = tarInp.attr("data-areaid");
		if(tarBtn.hasClass("disable")) return false;
		if(tarBtn.hasClass("plus")){
			
			newVal = Number(val)+1;
			
		}else{
			if(val=="0"){return false;}
			newVal = Number(val)-1;
		}
		that.changeCount(tarInp,areaid,storage,val,newVal);
	},
	aonCountBtnClick : function(that,e){
		
		var tarBtn = $(e.currentTarget);
		var tarInp = tarBtn.siblings(".formInp");
		var val = tarInp.val(), newVal=0;
		
		var storage = tarInp.attr("data-storage");
		var areaid = tarInp.attr("data-areaid");
		if(tarBtn.hasClass("disable")) return false;
		if(tarBtn.hasClass("plus")){
			newVal = Number(val)+1;
			
		}else{
			if(val=="0"){return false;}
			newVal = Number(val)-1;
		}
		that.changeCount(tarInp,areaid,storage,val,newVal);
	},
	//改变票数，增减或手动输入
	//changeCount : function(tarInp,areaid,storage,orignCount,newCount){
	changeCount : function(tarInp,areaid,storage,orignCount,newCount){
		//if(!tarInp || !areaid || !storage || typeof newCount=="undefined" || typeof newCount=="undefined") return false;
		//console.log(tarInp)
		storage = Number(storage);
		newCount = Number(newCount);
		tarInp.val(newCount);
		var minuBtn = tarInp.siblings(".sub");
		var addBtn = tarInp.siblings(".plus");
		var tprice = Number(tarInp.attr("data-tprice"));
		//alert(tprice)
		var inps = $("#proTable").find(".countInp");
		var totalCount = (function(){
			var totalCount = 0;
			inps.each(function(){
				totalCount += Number($(this).val());
			})
			return totalCount;
		})();
		var totalMoney = 0;
		var totalTicket = 0;
		// if(totalCount>storage){
			// alert("门票库存数量不足");
			// tarInp.val(orignCount);
			// return false;
		// }
		if(newCount==0){
			//minuBtn.addClass("disable");
			//addBtn.removeClass("disable");
			tarInp.val(newCount);
		//}
		// else if(totalCount==storage){
			// $("#proTable").find(".plus_"+areaid).addClass("disable");
			// minuBtn.removeClass("disable");
			// tarInp.val(newCount);
		}else{
			$("#proTable").find(".countInp").each(function(){
				var tarInp = $(this);
				var minuBtn = tarInp.siblings(".sub");
				var addBtn = tarInp.siblings(".plus");
				addBtn.removeClass("disable");
				if(tarInp.val()!="0"){
					//minuBtn.removeClass("disable");
				}else{
					//minuBtn.addClass("disable");
				}
			})
		}
		tarInp.parents(".ticket_c").find(".num").text('￥'+tprice*newCount);
		//tarBtn.parents().find(".num").text(tprice*newCount);
		// $("#proTable").find(".smallTotalNum").each(function(){
			// totalMoney += Number($(this).text());
			// //alert(totalMoney)
		// });
		$("#proTable").find(".formInp").each(function(){
			totalTicket += Number($(this).val());
		});
		$("#summoney").text(totalMoney);
		$("#sumtnum").text(totalTicket);
		this.fire("countChanged",orignCount,newCount);
	},
	//根据场次更改库存
	changeStorage : function(data){
		if(!data) return false;
		data = data.split("|");
		for(var i in data){
			var d = data[i];
			var arr = d.split(",");
			var storage = arr[1];
			var tarCountInp = $("#proTable").find(".countInp_"+arr[0]);
			$("#storage_td_"+arr[0]).text(storage);
			tarCountInp.attr("data-storage",storage);
			if(Number(storage)>0){
				tarCountInp.siblings(".plusBtn").removeClass("disable");
			}
		}
	}
});
new Order({container:$("#ticket_presale")});
new Product({container:$("#ticket_presale")});
$(".show_class").toggle( 
		function () { 
			$(".ticket_con").css({height:"auto"});
			$(".ticket_con").removeClass("overflow");
			$(".show_class").text("隐藏部分");
		 }, 
		  function () { 
			 $(".ticket_con").animate({height:"285px"});
			 $(".ticket_con").addClass("overflow");
			 $(".show_class").text("显示全部");
		}
	 );
new tarBtn({container:$("#ticket_presale")});
new search_all({container:$("#ticket_presale")});